package com.homework.linglong.service.impl;

import com.homework.linglong.common.model.EmpMsgCommon;
import com.homework.linglong.common.service.ReturnCode;
import com.homework.linglong.dao.mbg.EmpMsgDao;
import com.homework.linglong.entity.mbg.EmpMsg;
import com.homework.linglong.entity.mbg.EmpMsgExample;
import com.homework.linglong.entity.mbg.User;
import com.homework.linglong.service.EmpMsgService;
import com.homework.linglong.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class EmpMsgServiceImpl implements EmpMsgService {
    @Autowired
    EmpMsgDao empMsgDao;
    @Autowired
    UserService userService;

    private final EmpMsgExample msgExample;

    EmpMsgServiceImpl(){
        msgExample = new EmpMsgExample();
    }

    @Override
    public List<EmpMsg> getUnVerifiedMsgList() {
        msgExample.clear();
        msgExample.createCriteria().andStateEqualTo(EmpMsgCommon.State.UnVerified.value);
        return empMsgDao.selectByExample(msgExample);
    }

    @Override
    public List<EmpMsg> getUnderUseMsgList() {
        msgExample.clear();
        msgExample.createCriteria().andStateEqualTo(EmpMsgCommon.State.UnderUse.value);
        return empMsgDao.selectByExample(msgExample);
    }

    @Override
    public List<EmpMsg> getUserMsgList() {
        msgExample.clear();
        User user = userService.getCurrentUser();
        msgExample.createCriteria().andUserIdEqualTo(user.getId());
        return empMsgDao.selectByExample(msgExample);
    }

    @Override
    public int updateUnverifiedEmpMsg(@NonNull Integer empMsgId, EmpMsg empMsg) {
        if(!empMsgId.equals(empMsg.getId())){
            return ReturnCode.badRequest;
        }
        EmpMsg msg = empMsgDao.selectByPrimaryKey(empMsgId);
        if(!canEmpMsgUpdate(msg)){
            return ReturnCode.forbidden;
        }
        if(empMsgDao.updateByPrimaryKeySelective(empMsg) == 1){
            return ReturnCode.success;
        }
        return ReturnCode.unKnownError;
    }

    @Override
    public EmpMsg getMsgById(Integer msgId) {
        return empMsgDao.selectByPrimaryKey(msgId);
    }

    @Override
    public int verifyMsg(Integer msgId) {
        EmpMsg msg = new EmpMsg();
        msg.setId(msgId);
        msg.setState(EmpMsgCommon.State.UnderUse.value);
        return empMsgDao.updateByPrimaryKey(msg);
    }

    @Override
    public int addEmpMsg(EmpMsg empMsg) {
        User user = userService.getCurrentUser();
        empMsg.setUserId(user.getId());
        return empMsgDao.insert(empMsg);
    }


    private boolean canEmpMsgUpdate(EmpMsg msg){
        return msg.getState().equals(EmpMsgCommon.State.UnVerified.value);
    }
}
